<?php

namespace app\controller\admin;

use app\base\BaseEncryptController;
use app\libs\Util;
use app\model\agency\AgencyEarningsModel;
use app\model\agency\AgencyModel;
use app\model\system\SysConfigModel;
use app\model\user\UserModel;
use think\Request;


/**
 * Agent 代理商
 * Class Agent
 * @package app\controller
 */
class Agency extends BaseEncryptController
{
    protected function initialize()
    {
        parent::initialize();
        $this->model = new AgencyModel();
    }

    /**
     * 分页列表
     * @param string $status
     * @param string $keyword
     * @param int $page
     * @param int $limit
     * @return \think\response\Json
     */
    public function getPage($status = '', $keyword = '', $page = 1, $limit = 10)
    {
        $data = $this->model->getPageData($status, $keyword, $page, $limit);
        return self::returnMsg(1, [
            'totalCount' => $data['total'],
            'currentPage' => $data['current'],
            'pageList' => $data['dataList']
        ]);
    }

    /**
     * 单条信息
     * @param $id
     * @return \think\response\Json
     */
    public function getInfo($id)
    {
        $data = $this->model->getInfoOne($id);

        if (!empty($data)) {
            return self::returnMsg(1, $data);
        } else {
            return self::returnMsg(1001);
        }
    }

    /**
     * 保存
     * @param Request $request
     * @return \think\response\Json
     */
    public function onSave(Request $request)
    {
        $formData = $request->param();
        $is_add = false;//是否添加
        if (empty($formData['id'])) {
            $is_add = true;
            $validate = 'app\validate\AgencyValidate.add';
        } else {
            $validate = 'app\validate\AgencyValidate.save';
        }
        $result = $this->validate($formData, $validate);
        if (isset($formData['create_time']) || isset($formData['update_time'])) {
            $formData['create_time'] = strtotime($formData['create_time']) ? strtotime($formData['create_time']) : $formData['create_time'];
            $formData['update_time'] = strtotime($formData['update_time']) ? strtotime($formData['update_time']) : $formData['update_time'];
        }
        if ($is_add) {
            $res = $this->model->get_user_exist($formData['agency_login_username']);//判断是否存在
            if ($res) {
                return self::returnMsg(991, [], '登录账号已存在');
            }
        }
        if (true !== $result) {
            return self::returnMsg(991, [], $result);
        } else {
            $formData['agency_login_password'] = password_hash($formData['agency_login_password'], PASSWORD_BCRYPT);//密码
            $ret = $this->model->saveData($formData, false, false);//修改是否添加进缓存。。。
            if (false !== $ret['flag']) {
                return self::returnMsg(1);
            } else {
                return self::returnMsg(0);
            }
        }
    }

    /**
     * 获取坐标
     * @param Request $request
     * @return \think\response\Json
     */
    public function getLngLat(Request $request)
    {
        $address = $request->post("address");
        if (!$address) {
            return self::returnMsg(0, [], '请输入地址');
        }
        $SysConfigModel = new SysConfigModel();
        $tx_service_key = $SysConfigModel->getInfo(1, 'tx_service_key')['tx_service_key'];//获取腾讯key
        $Util = new Util();
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?address=" . $address . "&key=" . $tx_service_key;//获取腾讯坐标
        $res = json_decode($Util->httpGet($url), true);
        if ($res['status'] == 0) {
            return self::returnMsg(1, $res['result']['location']);
        } else {
            return self::returnMsg(0, [], $res['msg']);
        }
    }

    /**
     * 修改密码
     * @param Request $request
     * @return \think\response\Json
     */
    public function onEditPassword(Request $request)
    {
        $formData = [
            "id" => $request->post("id"),
            "agency_login_password" => $request->post("password"),
        ];
        $validate = 'app\validate\AgencyValidate.uppwd';
        $result = $this->validate($formData, $validate);
        if (true !== $result) {
            return self::returnMsg(991, [], $result);
        }
        $formData['agency_login_password'] = password_hash($formData['agency_login_password'], PASSWORD_BCRYPT);//密码

        $ret = $this->model->saveData($formData, false, false);//修改是否添加进缓存。。。
        if (false !== $ret['flag']) {
            return self::returnMsg(1);
        } else {
            return self::returnMsg(0);
        }
    }

    /**
     * 删除
     * @param $id
     * @return \think\response\Json
     */
    public function onDelete($id)
    {
        $flag = $this->model::destroy(['id' => $id]);
        if (false !== $flag) {
            $user_model = new UserModel();
            $user_model->clearAgency('', $id);
            $this->model->delRedis($id);
            $this->model->redis->zRem($this->model->redis_key . ':rank', $id);
            $this->model->addToRecycle($id, 'AgencyModel', '代理商管理', $this->currentUser['user_id'], $this->currentUser['user_type'], 'agency');
            return self::returnMsg(1);
        } else {
            return self::returnMsg(1002);
        }
    }

    /**
     * 上线状态
     * @param Request $request
     * @return \think\response\Json
     */
    public function onStatus(Request $request)
    {
        $formData = [
            'id' => $request->param('id'),
            'agency_status' => $request->param('status'),
        ];

        $validate = 'app\validate\AgencyValidate.upstatus';
        $result = $this->validate($formData, $validate);
        if (true !== $result) {
            return self::returnMsg(991, [], $result);
        } else {
            $ret = $this->model->saveData($formData, false, false);
            if (false !== $ret['flag']) {
                return self::returnMsg(1);
            } else {
                return self::returnMsg(0);
            }
        }
    }

    /**
     *提现申请列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function getAgencyExtractPage(Request $request)
    {
        $formData = $request->param();
        $page = $formData['page'];
        $keyword = $formData['keyword'];
        $check = $formData['check'];
        $limit = $formData['limit'];
        $agency_earnings_model = new AgencyEarningsModel();
        $agency_earnings_model = $agency_earnings_model->alias('a')
            ->join("t_agency b", "a.agency_id=b.id")
            ->Keyword($keyword)
            ->where('a.type', 3);
        if (intval($check) !== -1) {
            $agency_earnings_model = $agency_earnings_model->where("a.check", $check);
        }
        $dataList = $agency_earnings_model
            ->field("a.*,b.agency_title,b.agency_name,b.agency_img,b.agency_login_username")
            ->paginate(['page' => $page, 'list_rows' => $limit], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $items = $dataList->items();
        return self::returnMsg(1, [
            'totalCount' => $total,
            'currentPage' => $current,
            'pageList' => $items
        ]);
    }

    /**
     *审核提现
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function onAgencyExtractStatus(Request $request)
    {
        $formData = $request->param();
        $id = $formData['id'];
        $detail = isset($formData['detail']) ? $formData['detail'] : "";
        $check = $formData['check'];
        $agency_earnings_model = new AgencyEarningsModel();
        $map = [
            'id' => $id
        ];
        $earnings = $agency_earnings_model->where($map)->find();
        if (empty($earnings)) {
            return self::returnMsg(0, [], '数据不存在');
        }
        $extract = [
            'id' => $id,
            'pay_sn' => $earnings['pay_sn'],
            'agency_id' => $earnings['agency_id'],
            'price' => $earnings['price'],
            'detail' => $detail,
            'check' => $check
        ];
        $res = $agency_earnings_model->checkEarningsExtract($extract);
        return self::returnMsg($res);
    }

    /**
     * 保存审核提现
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onAgencyExtractSave(Request $request)
    {
        $formData = $request->param();
        $agency_id = $formData['agency_id'];
        $price = $formData['price'];
        $res['code'] = 1;
        $res['msg'] = "参数有误";
        if (floatval($price) <= 0) {
            $res['code'] = 1;
            $res['msg'] = "提现金额有误";
        }
        $agency_model = new AgencyModel();
        $map = ['id' => $agency_id];
        $agency_data = $agency_model->where($map)->field('id,agency_price')->find();
        if (empty($agency_data)) {
            $res['code'] = 1;
            $res['msg'] = "代理商信息有误";
        }
        if (floatval($price) <= floatval($agency_data['agency_price'])) {
            $order_sn = date("YmdHis") . $agency_data['id'] . mt_rand(1000, 9999);
            $pay_sn = "extract" . date("YmdHis") . $agency_data['id'] . mt_rand(1000, 9999);
            $rest = $agency_model->changeEarnings($agency_data['id'], floatval($price), 3, 'extract', $order_sn, $pay_sn);
            if ($rest['code'] == 1) {
                $extract = [
                    'id' => $rest['id'],
                    'pay_sn' => $pay_sn,
                    'agency_id' => $agency_id,
                    'price' => $price,
                    'detail' => "提现 减少收益",
                    'check' => 0
                ];
                $agency_earnings_model = new AgencyEarningsModel();
                $res = $agency_earnings_model->checkEarningsExtract($extract);
            }
        }
        return self::returnMsg($res);
    }

    /**
     * 获取代理商提现详情
     * @param $id
     * @return \think\response\Json
     */
    public function onAgencyExtractInfo($id)
    {
        $agency_earnings_model = new AgencyEarningsModel();
        $data = $agency_earnings_model->alias('a')
            ->join("t_agency b", "a.agency_id=b.id")
            ->field("a.*,b.agency_title,b.agency_name,b.agency_img,b.agency_login_username")
            ->where('a.id', $id)->find();
        if (!empty($data)) {
            return self::returnMsg(1, $data);
        } else {
            return self::returnMsg(1001);
        }
    }

}
